package com.ming.common.handler;

import cn.hutool.core.util.StrUtil;
import com.ming.common.exception.BussiException;
import com.ming.common.CodeMsg;
import com.ming.common.Result;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 * 专门处理异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 只处理业务异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BussiException.class)
    public Object handlerBussiException(BussiException ex) {
        //打印异常信息
        ex.printStackTrace();
        //将异常信息封装成为Result 进行返回
        Integer code = ex.getCode();
        String msg = ex.getMsg();
        return new Result(code, msg);
    }

    /**
     * 处理shiro相关异常
     * @param ex
     * @return
     */
    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public Object handlerShiroException(ShiroException ex, HttpServletRequest request) {
        //一种是认证异常
        //第二种是鉴权异常
        //不管是谁 要先判断是ajax请求还是web请求  是ajax返回json  是web请求返回页面
        //校验请求方式
        boolean flag = isAjax(request);
        //认证异常
        if (ex instanceof UnknownAccountException && flag){
            return new Result(CodeMsg.USER_LOGIN_ERROR);
        }

        //权限验证
        if (ex instanceof AuthenticationException && flag){
            return new Result(CodeMsg.USER_NO_PERMISSION_ERROR);
        }
        return new Result();
    }

    /**
     * 判断是否是ajax请求
     * true是 - false不是
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request){
        String tag = request.getHeader("x-requested-with");
        return StrUtil.endWithIgnoreCase(tag,"XMLHttpRequest");
    }

}
